package cn.edu.hqu.cst.android.hxy.e4;

import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;
import android.util.Log;


public class MyService extends Service {
    private int count = 0;
    private boolean quit = false;
    private MyServiceBinder myServiceBinder = new MyServiceBinder();

    public MyService() {}

    @Override
    public IBinder onBind(Intent intent) {
        return myServiceBinder;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        // 开启子线程更新计数
        new Thread(() -> {
            while (!quit) {
                try {
                    Thread.sleep(1000); // 每秒递增
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                count++;
            }
        }).start();
    }

    class MyServiceBinder extends Binder {
        public int getCount() {
            return MyService.this.count;
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        quit = true;
        count = 0; // 将计数重置为 0
        Log.d("MyService", "Service destroyed");
    }
}
